package com.youxin.chat.user.manager;

import com.youxin.base.BaseResultCode;
import com.youxin.chat.user.enums.GroupMemberTypeEnum;
import com.youxin.chat.user.mapper.GroupMapper;
import com.youxin.chat.user.mapper.GroupMemberMapper;
import com.youxin.chat.user.mapper.UserGroupMapper;
import com.youxin.chat.user.model.GroupMember;
import com.youxin.chat.user.model.UserGroup;
import com.youxin.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * description: GroupManager <br>
 * date: 2020/2/27 14:51 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class GroupManager {

    private static final Logger logger = LoggerFactory.getLogger(GroupManager.class);

    @Resource
    private GroupMemberMapper groupMemberMapper;

    @Resource
    private UserGroupMapper userGroupMapper;

    @Resource
    private GroupMapper groupMapper;

    @Transactional
    public void addGroupMembers(List<GroupMember> groupMembers, List<UserGroup> userGroups) {
        groupMemberMapper.insertBatch(groupMembers);
        userGroupMapper.insertBatch(userGroups);
    }

    @Transactional
    public int removeMember(String groupNo, List<String> userNos) {
        groupMemberMapper.deleteByGroupNoAndUserNos(groupNo, userNos);
        userGroupMapper.deleteByGroupNoAndUserNos(groupNo, userNos);
        return 1;
    }

    @Transactional
    public int removeGroup(String groupNo) {
        groupMemberMapper.deleteByGroupNo(groupNo);
        userGroupMapper.deleteByGroupNo(groupNo);
        groupMapper.deleteByGroupNo(groupNo);
        return 1;
    }

    public boolean checkOperate(String userNo, String groupNo) {
        Integer type = groupMemberMapper.selectUserType(userNo, groupNo);
        if (GroupMemberTypeEnum.NORMAL.getType().equals(type)) {
            return false;
        } else {
            return true;
        }
    }

    @Transactional
    public void changeGroupMaster(String groupNo, String userNo) {
        int count = groupMapper.changeGroupMaster(groupNo, userNo);
        if (count < 1) {
            logger.error("群主设置失败，groupNo={},userNo={}", groupNo, userNo);
            return;
        }
        count = groupMemberMapper.cancelGroupMaster(groupNo);
        if (count < 1) {
            logger.error("取消群主设置失败，groupNo={},userNo={}", groupNo, userNo);
            throw new SystemException(BaseResultCode.COMMON_FAIL,"系统内部错误");
        }
        count = groupMemberMapper.setGroupMaster(userNo, groupNo);
        if (count < 1) {
            logger.error("群主设置失败，groupNo={},userNo={}", groupNo, userNo);
            throw new SystemException(BaseResultCode.COMMON_FAIL,"系统内部错误");
        }
    }

}
